package com.zprmb.udzt;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.zprmb.udzt.http.AjaxParams;
import com.zprmb.udzt.ll.BaseHelper;
import com.zprmb.udzt.util.Constant;
import com.zprmb.udzt.util.Regular;
import com.zprmb.udzt.util.TimeCount;
import com.zprmb.udzt.util.ToastUtil;
import com.zprmb.udzt.util.VolleryUtil;
import com.zprmb.udzt.util.VolleySingleton;
import com.zprmb.udzt.view.LoadingDialog;
import com.zprmb.udzt.vo.AuthFailureError;
import com.zprmb.udzt.vo.Request.Method;
import com.zprmb.udzt.vo.Response;
import com.zprmb.udzt.vo.VolleyError;
import com.zprmb.udzt.vo.toolbox.ImageRequest;
import com.zprmb.udzt.vo.toolbox.JsonObjectRequest;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class V6RegisterActivity extends BaseActivity implements OnClickListener {
    private EditText user_phone_num, user_imgcaptcha, user_captcha;
    private Button btn_send_mes;
    private View view_line;
    private String csrf;
    private int code = 0;
    private Button btn_next;
    private TimeCount timeCount;
    private LoadingDialog dialog;
    private ImageView img_imgcaptcha, img_clear_user;
    private RelativeLayout rl_imgcaptcha;
    //	private RequestQueue mQueue;
    private TextView jump_login;
    private TextView tv_voice_code;
    private TextView enterprise_tel;
    private TextView tv_comment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.v6_register_activity);
//		DefaultHttpClient httpclient = new DefaultHttpClient();
//        CookieStore cookieStore = new BasicCookieStore();
//        httpclient.setCookieStore(cookieStore);
//        HttpStack httpStack = new HttpClientStack(httpclient);   
//        mQueue = Volley.newRequestQueue(this, httpStack);
        BbtApplication.getInstance().addActvity(this);
        setTitle("会员注册", this);
        setgoback(this);
        dialog = new LoadingDialog(this);
        jump_login = (TextView) findViewById(R.id.jump_login);
        img_imgcaptcha = (ImageView) findViewById(R.id.img_imgcaptcha);
        user_phone_num = (EditText) findViewById(R.id.user_phone_num);
        user_imgcaptcha = (EditText) findViewById(R.id.user_imgcaptcha);
        user_captcha = (EditText) findViewById(R.id.user_captcha);
        img_imgcaptcha = (ImageView) findViewById(R.id.img_imgcaptcha);
        enterprise_tel = (TextView) findViewById(R.id.enterprise_tel);
        btn_send_mes = (Button) findViewById(R.id.btn_send_mes);
        view_line = (View) findViewById(R.id.view_line);
        rl_imgcaptcha = (RelativeLayout) findViewById(R.id.rl_imgcaptcha);
        btn_next = (Button) findViewById(R.id.btn_next);
        tv_voice_code = (TextView) findViewById(R.id.tv_voice_code);
        img_clear_user = (ImageView) findViewById(R.id.img_clear_user);
        tv_comment = (TextView) findViewById(R.id.tv_comment);
        tv_voice_code.setText(Html.fromHtml("收不到短信？点击获取" + "<font color='#00aaee'>语音验证码</font>"));
        tv_voice_code.setOnClickListener(this);
        img_clear_user.setOnClickListener(this);
//		img_reg_bg.setImageBitmap(BitmapUtils.readBitMap(this, R.drawable.v6_login_bg));
        img_imgcaptcha.setOnClickListener(this);
        jump_login.setOnClickListener(this);
        btn_next.setOnClickListener(this);
        btn_send_mes.setOnClickListener(this);
        enterprise_tel.setOnClickListener(this);
        timeCount = new TimeCount(60000, 100, btn_send_mes, tv_voice_code);

        user_phone_num.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO Auto-generated method stub

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub
                if ("".equals(s.toString())) {
                    img_clear_user.setVisibility(View.GONE);
                } else {
                    img_clear_user.setVisibility(View.VISIBLE);
                }
                if (Regular.isMobileNO(s.toString())) {
                    btn_send_mes.setVisibility(View.VISIBLE);
                    tv_voice_code.setVisibility(View.VISIBLE);
                } else {
                    btn_send_mes.setVisibility(View.GONE);
                    tv_voice_code.setVisibility(View.GONE);
                }
            }
        });

//		initcaptcha();
    }

    private void showDialog() {
        if (dialog.isShowing() == false & !V6RegisterActivity.this.isFinishing()) {
            dialog.show();
        }
    }

    private void dissmissDialog() {
        if (dialog != null & !V6RegisterActivity.this.isFinishing()) {
            dialog.dismiss();
        }
    }

    private void initcaptcha() {
        // TODO Auto-generated method stub
        ImageRequest imageRequest = new ImageRequest(
                Constant.URL + "/captcha.png",
                new Response.Listener<Bitmap>() {
                    @Override
                    public void onResponse(Bitmap response) {
                        img_imgcaptcha.setImageBitmap(response);
                    }
                }, 0, 0, Config.RGB_565, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                img_imgcaptcha.setImageResource(R.drawable.bbt_bg);
            }
        });
        VolleySingleton.getInstance(V6RegisterActivity.this).addToRequestQueue(imageRequest);

    }

    private void initData(final int approach) {
        // 这个接口返回的请求头里有3个参数，，前两个暂时写死！
        VolleryUtil vollery = new VolleryUtil() {

            @Override
            public void onUpDate(JSONObject jsonObject) {
                // TODO Auto-generated method stub
                try {

                    if (jsonObject.optInt("success") == 1) {
                        csrf = jsonObject.getJSONObject("data").optString(
                                "csrf");
                        initmessage(approach);
                    } else {

                        Toast.makeText(V6RegisterActivity.this,
                                jsonObject.optString("comment"), 0).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError() {
                // TODO Auto-generated method stub

            }
        };
        vollery.setHeaders("appId", "bbt3.0:android");
        vollery.setHeaders("appSecret", "RH89xcYh");
        vollery.setHeaders("appVersion", getAppVersion());
        vollery.setRequestMethod(1);

        vollery.execute(this, Constant.URL + "api/csrf", "");
    }

    @SuppressWarnings("deprecation")
    private void initmessage(final int approach) {
        showDialog();
        AjaxParams params = new AjaxParams();
        if (code == 1) {

            params.put("captcha", user_imgcaptcha.getText().toString());
        }
        try {
            params.put("secureCode", URLEncoder.encode(encrypt(getdeviceId() + "|" + System.currentTimeMillis(), getPublicKey())));
            Log.e("时间戳", System.currentTimeMillis() + "");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        params.put("mobile", user_phone_num.getText().toString());
        params.put("approach", approach + "");
        Log.e("params", params.toString());

        JsonObjectRequest json = new JsonObjectRequest(Method.POST,
                Constant.URL + "api/v6/register/getMobileCaptchaForApp?" + params.toString(), null, new Response.Listener<JSONObject>() {
            public void onResponse(JSONObject response) {
                Log.e("短信", response.toString());
                dissmissDialog();
                if (response.optInt("success") == 1) {
                    timeCount.start();
                    if (approach == 1) {

                        tv_voice_code.setText("您将会接到电话播报验证码，请保持手机畅通");
                    }
                } else {
                    if (response.optString("code").equals("1")) {
                        initcaptcha();
                        code = response.optInt("code");
                        view_line.setVisibility(View.VISIBLE);
                        rl_imgcaptcha.setVisibility(View.VISIBLE);
                    } else {
                        initcaptcha();
                    }
                    if (!response.optString("comment").equals("")) {


                        Toast.makeText(V6RegisterActivity.this, response.optString("comment"), 2000).show();
                    }
                }
            }
        }, new Response.ErrorListener() {
            public void onErrorResponse(VolleyError error) {
                dissmissDialog();

            }
        }) {
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("csrf", csrf);
                return headers;
            }
        };
        VolleySingleton.getInstance(V6RegisterActivity.this).addToRequestQueue(json);


    }

    private void registerNextTo() {
        showDialog();
        AjaxParams params = new AjaxParams();
        params.put("mobileCaptcha", user_captcha.getText().toString().trim());
        params.put("mobile", user_phone_num.getText().toString().trim());


        JsonObjectRequest json = new JsonObjectRequest(Method.POST,
                Constant.URL + "/api/v6/register/checkMobileCaptcha?" + params.toString(), null, new Response.Listener<JSONObject>() {
            public void onResponse(JSONObject response) {
                dissmissDialog();
                Log.e("下一步", response.toString());
                if (response.optInt("success") == 1) {
                    Intent intent = new Intent(V6RegisterActivity.this, V6Register_Confirm.class);
                    intent.putExtra("mobile", user_phone_num.getText().toString());
                    startActivity(intent);
                    finish();
                } else {
                    timeCount.cancel();
                    btn_send_mes.setText("发送验证码");
                    btn_send_mes.setClickable(true);
                    btn_send_mes.setBackgroundResource(R.drawable.v6button);
                    initcaptcha();
                    view_line.setVisibility(View.VISIBLE);
                    rl_imgcaptcha.setVisibility(View.VISIBLE);
                    if (!response.optString("comment").equals("")) {
                        changeCommentStatus(1, response.optString("comment"));
//								ToastUtil.showCenterToast(V6RegisterActivity.this,response.optString("comment"));
                    }
                }
            }
        }, new Response.ErrorListener() {
            public void onErrorResponse(VolleyError error) {

                dissmissDialog();
            }
        }) {
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                headers.put("csrf", csrf);
                headers.put("UserAgent", "rmbbox_android");
                headers.put("token", getToken());
                headers.put("client", "android");
                return headers;
            }
        };

        VolleySingleton.getInstance(V6RegisterActivity.this).addToRequestQueue(json);

    }

    public boolean dispatchTouchEvent(MotionEvent ev) {
        // TODO Auto-generated method stub
        if (tv_comment != null) {

            if (tv_comment.getVisibility() == View.VISIBLE) {
                tv_comment.setVisibility(View.GONE);
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    private void changeCommentStatus(int status, String comment) {
        if (status == 1) {
            if (tv_comment.getVisibility() == View.GONE) {
                tv_comment.setVisibility(View.VISIBLE);
                tv_comment.setText(comment);
            }
        } else {
            if (tv_comment.getVisibility() == View.VISIBLE) {
                tv_comment.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.btn_send_mes:
                initData(0);
                break;
            case R.id.btn_next:
                if (!Regular.isMobileNO(user_phone_num.getText().toString())) {
                    ToastUtil.showCenterToast(this, "请输入正确的手机号");
                    return;
                }
                if (user_captcha.getText().equals("")) {
                    ToastUtil.showCenterToast(this, "请输入短信验证码");
                    return;
                }
                registerNextTo();
              /*  Intent intent2 = new Intent(V6RegisterActivity.this, V6Register_Confirm.class);
                intent2.putExtra("mobile", user_phone_num.getText().toString());
                startActivity(intent2);
                finish();
*/
                break;
            case R.id.img_imgcaptcha:
                initcaptcha();
                break;

            case R.id.jump_login:
                if (getIntent().getIntExtra("webview", 0) == 1) {
                    Intent intent = new Intent(V6RegisterActivity.this, V6LoginActivity.class);
                    intent.putExtra("close", 1);
                    startActivity(intent);
                } else {

                    finish();
                }
                break;
            case R.id.img_clear_user:
                user_phone_num.setText("");
                break;
            case R.id.tv_voice_code:

                initData(1);
                break;
            case R.id.enterprise_tel:
                BaseHelper.showDialog2(this, "拨号", "400-0101-016", 1);
                break;
        }
    }

}
